package com.example.androidproject.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.androidproject.chat.pojo.ChatMessage;

import java.util.ArrayList;
import java.util.List;

public class MessageRepository {
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private String tableName;

    public MessageRepository(Context context, String tableName) {
        this.tableName = tableName;
        dbHelper = new DatabaseHelper(context, tableName);
        database = dbHelper.getWritableDatabase();
        dbHelper.createTable(database);
    }

    /**
     * 插入消息，并指定身份信息
     * @param message 要插入的消息内容
     * @param identity 身份标识，0 或 1
     */
    public void insertMessage(String message, int identity) {
        try {
            ContentValues values = new ContentValues();
            values.put(DatabaseHelper.COLUMN_MESSAGE, message);
            values.put(DatabaseHelper.COLUMN_IDENTITY, identity); // 添加身份信息
            database.insert(tableName, null, values);
        } catch (Exception e) {
            // 处理异常，例如记录日志或通知用户
            e.printStackTrace();
        }
    }

    /**
     * 获取所有消息，并返回身份信息
     * @return 包含消息及身份信息的列表
     */
    public List<ChatMessage> getAllMessages() {
        List<ChatMessage> messages = new ArrayList<>();
        Cursor cursor = database.query(
                tableName,
                new String[]{DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_MESSAGE, DatabaseHelper.COLUMN_IDENTITY},
                null, null, null, null, null
        );

        int idIndex = cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ID);
        int messageIndex = cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_MESSAGE);
        int identityIndex = cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_IDENTITY);

        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(idIndex);
                String message = cursor.getString(messageIndex);
                int identity = cursor.getInt(identityIndex);
                messages.add(new ChatMessage(id, message, identity));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return messages;
    }

    /**
     * 删除指定ID的消息
     * @param messageId 要删除的消息ID
     * @return 返回删除的记录数，通常是0或1
     */
    public int deleteMessageById(int messageId) {
        try {
            return database.delete(
                    tableName,
                    DatabaseHelper.COLUMN_ID + " = ?",
                    new String[]{String.valueOf(messageId)}
            );
        } catch (Exception e) {
            // 处理异常，例如记录日志或通知用户
            e.printStackTrace();
            return 0;
        }
    }

}
